package com.ellricky.baselib.ui.clue;


import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andr.common.http.callback.JOCallback;
import com.andr.common.permission.PermissionManager;
import com.andr.common.permission.Permissions;
import com.andr.common.util.DialUtil;
import com.andr.common.util.EmptyUtil;
import com.andr.common.util.ResUtil;
import com.andr.common.util.StrUtil;
import com.andr.common.util.ToastUtil;
import com.ellricky.baselib.BaseConstant;
import com.ellricky.baselib.R;
import com.ellricky.baselib.cache.LocalCacheUtil;
import com.ellricky.baselib.dialog.picker.EPickerStrListener;
import com.ellricky.baselib.dialog.picker.EPickerUtil;
import com.ellricky.baselib.entity.clue.MyClueDetailEntity;
import com.ellricky.baselib.http.HttpUtils;
import com.ellricky.baselib.http.callback.ECallback;
import com.ellricky.baselib.listener.OnTakePhotoListener;
import com.ellricky.baselib.ui.base.BaseDetailActivity;
import com.ellricky.baselib.ui.visit.VisitListActivity;
import com.ellricky.baselib.util.EAppUtil;
import com.ellricky.baselib.util.EDialogUtil;
import com.ellricky.baselib.widget.DetailItemView;
import com.flyco.roundview.RoundTextView;
import com.flyco.roundview.RoundViewDelegate;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.Nullable;

import static com.ellricky.baselib.BaseConstant.CLUE_TYPE_NO_WISH;
import static com.ellricky.baselib.BaseConstant.CLUE_TYPE_WAIT;
import static com.ellricky.baselib.BaseConstant.CLUE_TYPE_WISH;
import static com.ellricky.baselib.http.Api.API_CLUE_DETAIL;
import static com.ellricky.baselib.http.Api.API_RESEVE_COURSE;
import static com.ellricky.baselib.http.Api.API_UPDATE_CLUE_STATUS;

public class MyClueDetailActivity extends BaseDetailActivity implements EPickerStrListener {

    private TextView tvNameSex;

    private DetailItemView tvTel;
    private DetailItemView tvAge;
    private DetailItemView tvSchool;
    private DetailItemView tvClueFrom;

    private RoundTextView btnReserve;
    private RoundTextView btnVisit;

    private RelativeLayout rlWish;
    private RoundTextView btnWaitDeal;
    private RoundTextView btnHasWish;
    private RoundTextView btnNoWish;

    private ImageView ivCluePhone;


    private String backvisitId = "";
    private String customerId = "";
    private boolean reserve;

    private int resultCode;
    private String curFromClue = "";

    private EPickerUtil pickerUtil;
    private String confirmTime;

    // 执行校长角色不能操作线索数据
    private boolean presidentRole;

    private  String trueTel ="";


    @Override
    public int getContentLayout() {
        return R.layout.base_activity_my_clue_detail;
    }

    @Override
    public void initUIView() {
        super.initUIView();

        presidentRole = LocalCacheUtil.isPresidentRole();

        mTvTitle.setText(R.string.base_clue_detail);

        tvNameSex = findViewById(R.id.tvNameSex);

        tvTel = findViewById(R.id.tvTel);
        tvAge = findViewById(R.id.tvAge);
        tvSchool = findViewById(R.id.tvSchool);
        tvClueFrom = findViewById(R.id.tvClueFrom);

        btnReserve = findViewById(R.id.btnReserve);
        btnVisit = findViewById(R.id.btnVisit);

        rlWish = findViewById(R.id.rlWish);
        btnWaitDeal = findViewById(R.id.btnWaitDeal);
        btnHasWish = findViewById(R.id.btnHasWish);
        btnNoWish = findViewById(R.id.btnNoWish);
        ivCluePhone = findViewById(R.id.ivCluePhone);

        btnVisit.setOnClickListener(this);
        btnReserve.setOnClickListener(this);
        btnWaitDeal.setOnClickListener(this);
        btnHasWish.setOnClickListener(this);
        btnNoWish.setOnClickListener(this);
        ivCluePhone.setOnClickListener(this);

        pickerUtil = new EPickerUtil(this);

        loadDetail(id);
    }

    private void loadDetail(String id) {
        mPresenter.loadDetail(API_CLUE_DETAIL, id, new ECallback<MyClueDetailEntity>(this) {
            @Override
            public void onSuccess(MyClueDetailEntity data, String msg) {
                trueTel = data.getTrueTel();
                backvisitId = StrUtil.filterEmpty(data.getBackvisitId());
                customerId = StrUtil.filterEmpty(data.getCustomerId());

                tvNameSex.setText(
                        String.format("%s %s", StrUtil.filterEmpty(data.getName()), StrUtil.filterEmpty(data.getSexName()))
                );
                tvTel.setValue(
                        StrUtil.filterEmpty(data.getTel())
                );
                tvAge.setValue(
                        StrUtil.filterEmpty(data.getAgeName())
                );
                tvSchool.setValue(
                        StrUtil.filterEmpty(data.getFromSchool())
                );
                tvClueFrom.setValue(
                        StrUtil.filterEmpty(data.getComeClue())
                );

                if (presidentRole) {
                    btnReserve.setVisibility(View.GONE);
                    rlWish.setVisibility(View.GONE);
                } else {
                    btnReserve.setVisibility(View.VISIBLE);
                    reserve = data.hadReserveClass();
                    if (reserve) {
                        btnReserve.setText(R.string.base_reserved);
                    } else {
                        btnReserve.setText(R.string.base_reserve_tyk);
                    }

                    rlWish.setVisibility(View.VISIBLE);
                    curFromClue = "";
                    updateTabState(
                            StrUtil.filterEmpty(data.getFromClue()), true
                    );

                }


            }
        });
    }

    @Override
    protected void onClickView(View v) {
        super.onClickView(v);
        if (v == btnVisit) {
            EAppUtil.jumpPageWithId(this, VisitListActivity.class, backvisitId);
        } else if (v == btnReserve) {
//            if (!reserve)
//                pickerUtil.showReservePicker(confirmTime, this);
            if (!reserve)
                EAppUtil.jumpClassManage(this);
        } else if (v == btnWaitDeal) {
            updateTabState(CLUE_TYPE_WAIT, false);
        } else if (v == btnHasWish) {
            updateTabState(CLUE_TYPE_WISH, false);
        } else if (v == btnNoWish) {
            updateTabState(CLUE_TYPE_NO_WISH, false);
        }else if (v == ivCluePhone) {
            dial();
        }

    }


    @Override
    public void onSelectItem(final String content, int picPos, int pickType) {
        EDialogUtil.showReserveConfirmDialog(this, new OnTakePhotoListener() {
            @Override
            public void onClickItem(DialogInterface dialogInterface, int item) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("backvisitId", backvisitId);
                paramMap.put("appointDate", content);

                String url = EAppUtil.getApiHost() + API_RESEVE_COURSE;
                HttpUtils.getInstance().post(url, paramMap, new JOCallback(MyClueDetailActivity.this) {
                    @Override
                    public void onSuccess(JSONObject dataJO, String msg) {
                        loadDetail(id);
                    }
                });
            }
        });
    }

    private void updateTabState(final String fromClue, boolean init) {
        if (StrUtil.isEquals(fromClue, curFromClue)) return;
        if (init) {
            updateTabState(fromClue);
        } else {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", id);
            paramMap.put("fromClue", fromClue);
            String url = EAppUtil.getApiHost() + API_UPDATE_CLUE_STATUS;
            HttpUtils.getInstance().post(url, paramMap, new JOCallback(this) {
                @Override
                public void onSuccess(JSONObject dataJO, String msg) {
                    resultCode = BaseConstant.RESULT_CODE_DETAIL;
                    updateTabState(fromClue);
                }
            });
        }
    }

    private void updateTabState(String fromClue) {
        curFromClue = fromClue;
        enableRoundTv(btnWaitDeal, false);
        enableRoundTv(btnHasWish, false);
        enableRoundTv(btnNoWish, false);

        if (StrUtil.isEquals(CLUE_TYPE_WAIT, curFromClue)) {
            enableRoundTv(btnWaitDeal, true);
        } else if (StrUtil.isEquals(CLUE_TYPE_WISH, curFromClue)) {
            enableRoundTv(btnHasWish, true);
        } else if (StrUtil.isEquals(CLUE_TYPE_NO_WISH, curFromClue)) {
            enableRoundTv(btnNoWish, true);
        }
    }

    private void enableRoundTv(RoundTextView rtv, boolean enable) {
        RoundViewDelegate delegate = rtv.getDelegate();
        int black = ResUtil.getColor(this, R.color.common_main_black);
        int gray = ResUtil.getColor(this, R.color.common_gray_66);
        int gray_cc = ResUtil.getColor(this, R.color.base_color_cc);
        int white = ResUtil.getColor(this, R.color.common_main_white);
        if (enable) {
            delegate.setBackgroundColor(black);
            rtv.setTextColor(white);
        } else {
            delegate.setBackgroundColor(gray_cc);
            rtv.setTextColor(white);
        }

        rtv.setSelected(enable);
    }


    @Override
    public void onKeyBack(boolean isKeyBack) {
        // 切换tab
        if (resultCode > 0) setResult(resultCode);
        super.onKeyBack(isKeyBack);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void dial() {
        PermissionManager.getInstance()
                .setGrantResult(this)
                .requestPermissions(this, Permissions.CALL_PHONE);
    }


    @Override
    public void onGrantedAll() {
        super.onGrantedAll();
        if (trueTel != null) {
            if (EmptyUtil.isEmpty(trueTel)) {
                ToastUtil.show(this, "电话号码为空，无法拨打");
                return;
            }
            DialUtil.dial(this, trueTel);
        }

    }

    @Override
    public void onDenied(String... permission) {
        super.onDenied(permission);
        if (permission[0].equals(Permissions.CALL_PHONE)) {
            ToastUtil.show(this, "请打开打电话权限");
        }
    }
}